package util;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

/**
 * HTTP工具类
 *
 * @author Bosen 2024/2/5 14:08
 */
public class HttpUtils {

    public static void main(String[] args) throws Exception {
        // for(int i = 165; i <= 180; i++) {
        //     String url = "https://grayapi.xmnjdwx.com/test/Test_sendProductCodeStatus?page=" + i + "&size=" + 1000;
        //     HttpUtils.getRequest(url);
        // }
    }

    /**
     * GET
     */
    public static String getRequest(String url) throws Exception {
        String message = "";
        try {
            URL urlGet = new URL(url);
            HttpURLConnection http = (HttpURLConnection) urlGet.openConnection();
            http.setRequestMethod("GET");
            http.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
            http.setDoOutput(true);
            http.setDoInput(true);

            System.setProperty("sun.net.client.defaultConnectTimeout", "30000");// 连接超时30秒
            System.setProperty("sun.net.client.defaultReadTimeout", "30000"); // 读取超时30秒

            http.connect();

            InputStream is = http.getInputStream();
            int size = is.available();

            byte[] jsonBytes = new byte[size];
            is.read(jsonBytes);
            message = new String(jsonBytes, "UTF-8");

            is.close();

        } catch (Exception e) {
            e.printStackTrace();
        }
        return message;
    }

    /**
     * POST
     */
    public static String postRequest(String url, String param) throws Exception {
        PrintWriter out = null;
        BufferedReader in = null;
        String result = "";
        try {
            URL httpUrl = new URL(url);
            HttpURLConnection conn = (HttpURLConnection) httpUrl.openConnection();
            conn.setRequestMethod("POST");

            conn.setDoOutput(true);
            conn.setDoInput(true);
            conn.setUseCaches(false);
            conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");

            // 获取URLConnection对象对应的输出流
            out = new PrintWriter(conn.getOutputStream());
            // 发送请求参数
            out.print(param);
            // flush输出流的缓冲
            out.flush();
            // 定义BufferedReader输入流来读取URL的响应
            in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
            String line;
            while ((line = in.readLine()) != null) {
                result += line;
            }

        } catch (Exception e) {
            throw e;
        } finally {
            try {
                if (out != null) {
                    out.close();
                }
                if (in != null) {
                    in.close();
                }
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }
        return result;
    }

    /**
     * 多线程分页请求
     */
    public static void pageRequest(String url, int total, int size) {
        // 最大页数
        int maxPage = (int) Math.ceil(((double) total) / size);
        // 开线程池，最大100
        ExecutorService executor = Executors.newFixedThreadPool(Math.min(maxPage, 100));
        for (int page = 1; page <= maxPage; page++) {
            String finalUrl = url;
            int finalPage = page;
            executor.execute(() -> {
                long startTime = System.currentTimeMillis();
                String path = finalUrl + "?page=" + finalPage + "&size=" + size;
                try {
                    String res = HttpUtils.getRequest(path);
                    long endTime = System.currentTimeMillis();
                    System.out.println();
                    System.out.println("成功: page = " + finalPage + ", size = " + size);
                    System.out.println("用时: " + (endTime - startTime));
                    System.out.println("结果: " + res);
                    printPageResult(res);
                } catch (Exception e) {
                    throw new RuntimeException(e);
                }
            });
        }
        executor.shutdown();
        try {
            if (executor.awaitTermination(60, TimeUnit.SECONDS)) {
                System.out.println(list.size());
            }
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
    }

    public static List<String> list = new CopyOnWriteArrayList<>();

    public static void printPageResult(String string) {
        String[] result = string.trim()
                .replaceAll("\\[", "")
                .replaceAll("]", "")
                .split(",");
        list.addAll(Arrays.asList(result));
    }
}
